<?php
/**
 * Created by PhpStorm.
 * 地区表
 * User: caicm
 * Date: 2017/6/15
 * Time: 21:50
 */

namespace WMApi\Model;


use Think\Model;

class RegionModel extends Model {

    public function get_address($name, $level){

        $name = str_replace(array('省','市','区','县','自治区','自治州','自治镇','自治县','特别行政区'),'',$name);

        $where = "region_type = ".$level ." and region_name like '%".$name."%'";

        return $this->where($where)->find();

    }

    /**
     * 获取地址列表
     * Created By caicm
     * @param int $parent_id
     * @param int $region_id
     * @return mixed
     */
    public function get_region_list($parent_id=0, $region_id=0){

        $where = array(
            'parent_id' => $parent_id,
            'region_id' => $region_id
        );
        if($region_id==0) unset($where['region_id']);

        return $this->field('region_id,region_name,parent_id')->where($where)->select();

    }

    /**
     * 获取区域详情
     * Created By caicm
     * @param int $region_id
     * @param int $parent_id
     * @return mixed
     */
    public function get_region_info($region_id=0, $parent_id=0){

        $where = array(
            'r1.region_id' => $region_id,
            'r1.parent_id' => $parent_id
        );
        if($parent_id==0) unset($where['r1.parent_id']);

        $field = 'r1.region_id as district,r1.region_name as district_name';
        $field .= ',r2.region_id as city,r2.region_name as city_name';
        $field .= ',r3.region_id as province,r3.region_name as province_name';
        $join = ' left join sdx_region as r2 on r1.parent_id=r2.region_id';
        $join .= ' left join sdx_region as r3 on r2.parent_id=r3.region_id';

        return $this->alias('r1')->field($field)->join($join)->where($where)->find();

    }


}